import {
  LOGIN,
  LOGOUT
} from '../mutationTypes'
import{
  loginByPwd,
  logout
} from '../../api/profile'
import {getStorage, setStorage, removeStorage} from '../../util/storage'

const profile_userInfo = getStorage('profile_userInfo') 
const default_userInfo = {
  user_id: null,
  username: "",
  avatar: "default.jpg",
  mobile: "",
  email: "",
  balance: 0.0,
  gift_amount: 0.0,
  point: 0.0,
}
const state = {
  // 登录状态
  isLogin: getStorage('profile_isLogin') || false,
  // 个人信息
  userInfo: profile_userInfo || default_userInfo
  // 收货地址
}

const getters = {

}

const mutations = {
  [LOGIN](state, payload){
    state.isLogin = true
    state.userInfo = {...state.userInfo, ...payload}
  },
  [LOGOUT](state, payload){
    state.isLogin = false
    state.userInfo = default_userInfo
  },
}

const actions = {
  async [LOGIN]({commit}, payload){
    const data = await loginByPwd(payload)
    if(data.user_id){
      console.log(data);
      // 保存数据到state
      commit(LOGIN, data)
      // 这里应该保存token到localStorage. 
      //由于后台接口的缘故，暂时将用户信息保存到localStorage
      setStorage('profile_userInfo', data)
      setStorage('profile_isLogin',true)
      return data
    }else{
      throw new Error(data.message)
    }
  },
  async [LOGOUT]({commit}, payload){
    const res = await logout()
    commit(LOGOUT)
    removeStorage('profile_userInfo')
    removeStorage('profile_isLogin')
    return res
  },
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}